package com.huabo.system.service.impl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hbfk.config.YinMaiUrlStatic;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.BaseDao;
import com.hbfk.util.HttpClient;
import com.hbfk.util.JsonBean;
import com.hbfk.util.ResponseFormat;
import com.hbfk.util.YinMaiMd5Util;
import com.huabo.system.config.DateBaseConfig;
import com.huabo.system.mysql.entity.TblOrganizationMySql;
import com.huabo.system.mysql.entity.TblRoleMySql;
import com.huabo.system.mysql.entity.TblStaffMySql;
import com.huabo.system.mysql.entity.TblSystemSheetTableMySql;
import com.huabo.system.mysql.mapper.TblOrganizationMySqlMapper;
import com.huabo.system.mysql.mapper.TblRoleMySqlMapper;
import com.huabo.system.mysql.mapper.TblStaffMySqlMapper;
import com.huabo.system.mysql.mapper.TblSystemSheetTableMySqlMapper;
import com.huabo.system.oracle.entity.TblOrganization;
import com.huabo.system.oracle.entity.TblRole;
import com.huabo.system.oracle.entity.TblStaff;
import com.huabo.system.oracle.entity.TblSystemSheetTable;
import com.huabo.system.oracle.mapper.TblOrganizationMapper;
import com.huabo.system.oracle.mapper.TblRoleMapper;
import com.huabo.system.oracle.mapper.TblStaffMapper;
import com.huabo.system.oracle.mapper.TblSystemSheetTableMapper;
import com.huabo.system.service.YinMaiBusinessService;


@Service
public class YinMaiBusinessServiceImpl implements YinMaiBusinessService {

	@Resource
	private TblStaffMapper tblStaffMapper;
	
	@Resource
	private TblStaffMySqlMapper tblStaffMySqlMapper;
	
	@Resource
	private TblOrganizationMapper tblOrganizationMapper;
	
	@Resource
	private TblOrganizationMySqlMapper tblOrganizationMySqlMapper;
	
	@Resource
	private TblRoleMapper tblRoleMapper;
	
	@Resource
	private TblRoleMySqlMapper tblRoleMySqlMapper;
	
	@Resource
	private TblSystemSheetTableMapper tblSystemSheetTableMapper;
	
	@Resource
	private TblSystemSheetTableMySqlMapper tblSystemSheetTableMySqlMapper;
	

	@Override
	public JsonBean submit(String token, Integer fromId, String flowId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("Authorization",loginStaff.getYmToken()); 
		
		HashMap<String, Object> filedMap = new HashMap<String,Object>(0);
		filedMap.put("flowId",flowId);
		filedMap.put("id",fromId);
		filedMap.put("status",0);
		
		String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.getApprovalUser.replace("#{id}", "0"),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		JSONObject reJson = JSONObject.parseObject(result);
		Integer code = reJson.getInteger("code");
		if(code != 200) {
			return ResponseFormat.retParam(0, 80003, null);
		}
		
		result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.submitFlow.replace("#{id}", fromId+flowId),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
		reJson = JSONObject.parseObject(result);
		code = reJson.getInteger("code");
		if(code != 200) {
			return ResponseFormat.retParam(0, 80003, null);
		}
		
		Integer count = 0;
		if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
			count = this.tblSystemSheetTableMySqlMapper.selectCountFormFlow(fromId+flowId);
			if(count == 0){
				this.tblSystemSheetTableMySqlMapper.insertFormFlowTable(fromId+flowId,flowId);
			}else {
				this.tblSystemSheetTableMySqlMapper.updateFormFlowTable(fromId+flowId,flowId);
			}
		}else {
			count = this.tblSystemSheetTableMapper.selectCountFormFlow(fromId+flowId);
			if(count == 0){
				this.tblSystemSheetTableMapper.insertFormFlowTable(fromId+flowId,flowId);
			}else {
				this.tblSystemSheetTableMapper.updateFormFlowTable(fromId+flowId,flowId);
			}
		}
		return ResponseFormat.retParam(1, 200, null);
	}
	
	@Override
	public JsonBean getSystemFlowList(String token, TblSystemSheetTable sheet) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		Map<String,Object> dataMap = new HashMap<String,Object>(0);
		if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
			List<TblSystemSheetTableMySql> list = this.tblSystemSheetTableMySqlMapper.selectSystemFlowList(sheet);
			dataMap.put("list", list);
		}else {
			List<TblSystemSheetTable> list = this.tblSystemSheetTableMapper.selectSystemFlowList(sheet);
			dataMap.put("list", list);
		}
		
		return ResponseFormat.retParam(1, 200, dataMap);
	}
	
	
	@Override
	public JsonBean getWorkFlowList(String token, String workName, Integer tableId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		
		Map<String,Object> dataMap = new HashMap<String,Object>(0);
		if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
			List<TblSystemSheetTableMySql> list = this.tblSystemSheetTableMySqlMapper.selectWorkFlowList(tableId,loginStaff.getCurrentOrg().getOrgid(),workName);
			dataMap.put("list", list);
		}else {
			List<TblSystemSheetTable> list = this.tblSystemSheetTableMapper.selectWorkFlowList(tableId,loginStaff.getCurrentOrg().getOrgid(),workName);
			dataMap.put("list", list);
		}
		
		return ResponseFormat.retParam(1, 200, dataMap);
	}
	
	@Override
	public JsonBean saveWorkFlowFormInfo(String token, String workName, Integer tableId, String ymWorkId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("Authorization",loginStaff.getYmToken()); 
		
		String workId = null;
		//通过工作流名称获取引迈的工作流信息， 然后比对名称得到Id;
		if(ymWorkId != null && !"".equals(ymWorkId)) {
			workId = ymWorkId;
		}else {
			//访问接口获取所有权限
			HashMap<String, Object> filedMap = new HashMap<String,Object>(0);
			filedMap.put("keyword",workName);
			
			String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.getWorkFlowInfo,filedMap,headerMap,loginStaff,HttpClient.HTTPGET);
			JSONObject reJson = JSONObject.parseObject(result);
			
			JSONObject dateJson = reJson.getJSONObject("data");
			
			JSONObject pagination = dateJson.getJSONObject("pagination");
			
			Integer totalCount = pagination.getInteger("total");
			if(totalCount == 0) {
				return ResponseFormat.retParam(0, 80001, null);
			}
			
			Integer pageSize = pagination.getInteger("total");
			Integer totalPage = totalCount/pageSize;
			if(totalCount%pageSize != 0) {
				totalPage++;
			}
			Integer currentPage = 1;
			JSONArray listJson = null;
			JSONObject workJson = null;
			boolean flag = false;
			do {
				if(currentPage != 1) {
					filedMap.put("currentPage",currentPage);
					result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.getWorkFlowInfo,filedMap,headerMap,loginStaff,HttpClient.HTTPGET);
					reJson = JSONObject.parseObject(result);
					dateJson = reJson.getJSONObject("data");
				}
				listJson = dateJson.getJSONArray("list");
				for (int i = 0; i < listJson.size(); i++) {
					workJson = listJson.getJSONObject(i);
					if(workName.equals(workJson.getString("fullName"))) {
						flag = true;
						workId = workJson.getString("id");
						break;
					}
				}
				if(flag) {
					break;
				}
				currentPage++;
			} while (currentPage<totalPage);
		}
		
		if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
			if(ymWorkId != null && !"".equals(ymWorkId)){
				//修改
				this.tblSystemSheetTableMySqlMapper.UpdateSystemYmWork(tableId,workId,loginStaff.getCurrentOrg().getOrgid(),workName);
			}else {
				//新增
				this.tblSystemSheetTableMySqlMapper.InsertSystemYmWork(tableId,workId,loginStaff.getCurrentOrg().getOrgid(),workName);
			}
		}else {
			if(ymWorkId != null && !"".equals(ymWorkId)){
				//修改
				this.tblSystemSheetTableMapper.UpdateSystemYmWork(tableId,workId,loginStaff.getCurrentOrg().getOrgid(),workName);
			}else {
				//新增
				this.tblSystemSheetTableMapper.InsertSystemYmWork(tableId,workId,loginStaff.getCurrentOrg().getOrgid(),workName);
			}
		}
		
		return ResponseFormat.retParam(1, 200, null);
	}
	
	@Override
	public JsonBean singleSignMothed(String token) throws Exception {
        TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
			return ResponseFormat.retParam(0, 20006, null);
		}
		return DealUserToken.getYmTokenMothod(loginStaff);
	}

	
	
	@Override
	public JsonBean synchronizeOrgInfo(String token, Integer orgId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("Authorization",loginStaff.getYmToken()); 
		headerMap.put("content-type","application/json;charset=UTF-8");
		//同步所有公司信息到引迈
		//1.获取华博所有公司信息
		if(orgId != null) {
			if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
				TblOrganizationMySql company = this.tblOrganizationMySqlMapper.selectCompanyByIdForYm(orgId);
				this.insertSynchronizeOrgInfoMySql(company,headerMap,loginStaff);
				company = this.tblOrganizationMySqlMapper.selectCompanyByIdForYm(orgId);
				List<TblOrganizationMySql> deptList = this.tblOrganizationMySqlMapper.selectDeptListByOrgId(company.getOrgid());
				this.synchronizeDeptInfoMySql(deptList,headerMap,company.getPkYmOrgId(),loginStaff);
			}else {
				TblOrganization company = this.tblOrganizationMapper.selectCompanyByIdForYm(orgId);
				this.insertSynchronizeOrgInfo(company,headerMap,loginStaff);
				company = this.tblOrganizationMapper.selectCompanyByIdForYm(orgId);
				List<TblOrganization> deptList = this.tblOrganizationMapper.selectDeptListByOrgId(company.getOrgid());
				this.synchronizeDeptInfo(deptList,headerMap,company.getPkYmOrgId(),loginStaff);
			}
		}else {
			if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
				List<TblOrganizationMySql> companyList = this.tblOrganizationMySqlMapper.selectCompanyListParentId(-1);
				this.insertSynchronizeOrgInfoMySql(companyList,headerMap,null,loginStaff);
				List<TblOrganizationMySql> allComList = this.tblOrganizationMySqlMapper.selectAllCompanyList();
				List<TblOrganizationMySql> deptList = null;
				for (TblOrganizationMySql com : allComList) {
					deptList = this.tblOrganizationMySqlMapper.selectDeptListByOrgId(com.getOrgid());
					this.synchronizeDeptInfoMySql(deptList,headerMap,com.getPkYmOrgId(),loginStaff);
				}
			}else {
				List<TblOrganization> companyList = this.tblOrganizationMapper.selectCompanyListParentId(-1);
				this.insertSynchronizeOrgInfo(companyList,headerMap,null,loginStaff);
				List<TblOrganization> allComList = this.tblOrganizationMapper.selectAllCompanyList();
				List<TblOrganization> deptList = null;
				for (TblOrganization com : allComList) {
					deptList = this.tblOrganizationMapper.selectDeptListByOrgId(com.getOrgid());
					this.synchronizeDeptInfo(deptList,headerMap,com.getPkYmOrgId(),loginStaff);
				}
			}
		}
		return ResponseFormat.retParam(1, 200, null);
	}

	@Override
	public JsonBean synchronizeStaffInfo(String token, Integer orgId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("Authorization",loginStaff.getYmToken()); 
		String result = null;
		HashMap<String, Object> filedMap = null;
		List<List<String>> organizeIdsTree = null;
		List<String> orgIdList = null;
		String pkYmStaffId = null;
		String pkYmOrgId = null;
		if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
			String orgIds = "";
				orgIds = this.getDeptIdsByOrgIdMySql(orgId.toString(),orgIds);
			pkYmOrgId = this.tblOrganizationMySqlMapper.selectYmPkOrgid(new BigDecimal(orgId));
			List<TblStaffMySql> staffList = this.tblStaffMySqlMapper.selectAllyinMaiStaffList(orgIds);
			for (TblStaffMySql staff : staffList) {
				filedMap = new HashMap<String,Object>(0);
				organizeIdsTree = new ArrayList<List<String>>(0);
				orgIdList = new ArrayList<String>(0);
				orgIdList.add(pkYmOrgId);
				organizeIdsTree.add(orgIdList);
				
				if(staff.getPkYmStaffId() != null && !"".equals(staff.getPkYmStaffId())) {
					//修改
					//id
					filedMap.put("account",staff.getUsername());
					filedMap.put("email", staff.getEmail());
					filedMap.put("enabledMark", 1);
					filedMap.put("gender", 3);
					filedMap.put("mobilePhone", staff.getMiblephone());
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("organizeId", pkYmOrgId);
					filedMap.put("realName", staff.getRealname());
					filedMap.put("roleId", staff.getRoleNames());
					filedMap.put("sortCode", 0);
					filedMap.put("id", staff.getPkYmStaffId());
					DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.updateStaffUrl+"/"+staff.getPkYmStaffId(),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
				}else {
					//新增
					filedMap.put("account",staff.getUsername());
					filedMap.put("email", staff.getEmail());
					filedMap.put("enabledMark", 1);
					filedMap.put("gender", 3);
					filedMap.put("mobilePhone", staff.getMiblephone());
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("organizeId", pkYmOrgId);
					filedMap.put("realName", staff.getRealname());
					filedMap.put("roleId", staff.getRoleNames());
					filedMap.put("sortCode", 0);
					DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveStaffUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
					pkYmStaffId = this.getYmPkStaffIdByStaffId(staff.getUsername(),staff.getOrgname());
					this.tblStaffMySqlMapper.updatePkYmStaffIdByStaffId(pkYmStaffId,staff.getStaffid());
					filedMap.clear();
					filedMap.put("id", pkYmStaffId);
					filedMap.put("userPassword", YinMaiMd5Util.getStringMd5(YinMaiUrlStatic.ymPassword).toLowerCase());
					filedMap.put("validatePassword", YinMaiMd5Util.getStringMd5(YinMaiUrlStatic.ymPassword).toLowerCase());
					DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.updatePasswordUrl.replace("#{id}", pkYmStaffId),filedMap,headerMap,loginStaff,"post");
				}
			}
			
		}else {
			pkYmOrgId = this.tblOrganizationMapper.selectYmPkOrgid(new BigDecimal(orgId));
			List<TblStaff> staffList = this.tblStaffMapper.selectAllyinMaiStaffList(orgId);
			for (TblStaff staff : staffList) {
				filedMap = new HashMap<String,Object>(0);
				organizeIdsTree = new ArrayList<List<String>>(0);
				orgIdList = new ArrayList<String>(0);
				orgIdList.add(pkYmOrgId);
				organizeIdsTree.add(orgIdList);
				
				if(staff.getPkYmStaffId() != null && !"".equals(staff.getPkYmStaffId())) {
					//修改
					//id
					filedMap.put("account",staff.getUsername());
					filedMap.put("email", staff.getEmail());
					filedMap.put("enabledMark", 1);
					filedMap.put("gender", 3);
					filedMap.put("mobilePhone", staff.getMiblephone());
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("organizeId", pkYmOrgId);
					filedMap.put("realName", staff.getRealname());
					filedMap.put("roleId", staff.getRoleNames());
					filedMap.put("sortCode", 0);
					filedMap.put("id", staff.getPkYmStaffId());
					DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.updateStaffUrl+"/"+staff.getPkYmStaffId(),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
				}else {
					//新增
					filedMap.put("account",staff.getUsername());
					filedMap.put("email", staff.getEmail());
					filedMap.put("enabledMark", 1);
					filedMap.put("gender", 3);
					filedMap.put("mobilePhone", staff.getMiblephone());
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("organizeId", pkYmOrgId);
					filedMap.put("realName", staff.getRealname());
					filedMap.put("roleId", staff.getRoleNames());
					filedMap.put("sortCode", 0);
					DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveStaffUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
					pkYmStaffId = this.getYmPkStaffIdByStaffId(staff.getUsername(),staff.getOrgname());
					this.tblStaffMapper.updatePkYmStaffIdByStaffId(pkYmStaffId,staff.getStaffid());
					filedMap.clear();
					filedMap.put("id", pkYmStaffId);
					filedMap.put("userPassword", YinMaiMd5Util.getStringMd5(YinMaiUrlStatic.ymPassword).toLowerCase());
					filedMap.put("validatePassword", YinMaiMd5Util.getStringMd5(YinMaiUrlStatic.ymPassword).toLowerCase());
					DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.updatePasswordUrl.replace("#{id}", pkYmStaffId),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
				}
			}
		}
		return ResponseFormat.retParam(1, 200, null);
	}



	private String getDeptIdsByOrgIdMySql(String orgId, String orgIds) throws Exception {
		String oIds = this.tblOrganizationMySqlMapper.selectOrgIdsByParentIds(orgId);
		if(oIds != null && !"".equals(oIds)) {
			orgIds += oIds;
			this.getDeptIdsByOrgIdMySql(oIds, orgIds);
		}
		return orgIds;
	}



	private String getYmPkStaffIdByStaffId(String username, String pkOrgid) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String fid = null;
		try {
			con = BaseDao.getInstance().getConnection();
			ps = con.prepareStatement("SELECT F_Id FROM base_user WHERE F_Account = '"+username+"' AND F_OrganizeId = '"+pkOrgid+"'");
			rs = ps.executeQuery();
			
			while (rs.next()) {
				fid = rs.getString("F_Id");
			}
		}finally {
			BaseDao.getInstance().close(con,rs,ps);
		}
		return fid;
	}

	@Override
	public JsonBean synchronizeRoleInfo(String token,Integer orgId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if (loginStaff == null) {
		    return ResponseFormat.retParam(0, 20006, null);
		}
		
		Map<String, String> headerMap = new HashMap<>();
		headerMap.put("Authorization",loginStaff.getYmToken());
		List<List<String>> organizeIdsTree = null;
		List<String> orgIdList = null;
		String pkYmRoleId = null;
		JSONObject reJson = null;
		JSONObject dataJson = null;
		
		//访问接口获取所有权限
		HashMap<String, Object> filedMap = new HashMap<String,Object>(0);
		filedMap.put("moduleIds","");
		filedMap.put("type","module");
		
		String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.authorityAllUrl.replace("#{id}", "0"),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		reJson = JSONObject.parseObject(result);
		dataJson = null;
		JSONArray moduleStrs = null;
		JSONArray moduleArray = null;
		JSONArray ptarray = null;
		JSONArray childrenArr = null;
		if("200".equals(reJson.getString("code"))) {
			dataJson = reJson.getJSONObject("data");
			moduleStrs = dataJson.getJSONArray("all");
			moduleArray = dataJson.getJSONArray("list");
			JSONObject module = null;
			for (int i = 0; i < moduleArray.size(); i++) {
				module = moduleArray.getJSONObject(i);
				if(YinMaiUrlStatic.rightNames.indexOf(module.getString("fullName")) != -1) {
					ptarray = new JSONArray();
					ptarray.add(module.getString("id"));
					childrenArr =  module.getJSONArray("children");
					for (int k = 0; k < childrenArr.size(); k++) {
						module = childrenArr.getJSONObject(k);
						ptarray.add(module.getString("id"));
					}
				}
			}
			
		}
		
		filedMap.put("type","button");
		result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.authorityAllUrl.replace("#{id}", "0"),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		reJson = JSONObject.parseObject(result);
		dataJson = null;
		JSONArray buttonStrs = null;
		if("200".equals(reJson.getString("code"))) {
			dataJson = reJson.getJSONObject("data");
			buttonStrs = dataJson.getJSONArray("all");
		}
		
		filedMap.put("type","column");
		result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.authorityAllUrl.replace("#{id}", "0"),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		reJson = JSONObject.parseObject(result);
		dataJson = null;
		JSONArray columnStrs = null;
		if("200".equals(reJson.getString("code"))) {
			dataJson = reJson.getJSONObject("data");
			columnStrs = dataJson.getJSONArray("all");
		}
		
		filedMap.put("type","form");
		result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.authorityAllUrl.replace("#{id}", "0"),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		reJson = JSONObject.parseObject(result);
		dataJson = null;
		JSONArray formStrs = null;
		if("200".equals(reJson.getString("code"))) {
			dataJson = reJson.getJSONObject("data");
			formStrs = dataJson.getJSONArray("all");
		}
		
		filedMap.put("type","resource");
		result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.authorityAllUrl.replace("#{id}", "0"),filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		reJson = JSONObject.parseObject(result);
		dataJson = null;
		JSONArray resourceStrs = null;
		if("200".equals(reJson.getString("code"))) {
			dataJson = reJson.getJSONObject("data");
			resourceStrs = dataJson.getJSONArray("all");
		}
		
		
		if(DateBaseConfig.DATABASETYPE.equals("MySql")) {
			List<TblRoleMySql> roleList = this.tblRoleMySqlMapper.selectAllRoleListToYinMai(orgId);
			for (TblRoleMySql role : roleList) {
				filedMap = new HashMap<String,Object>(0);
				organizeIdsTree = new ArrayList<List<String>>(0);
				orgIdList = new ArrayList<String>(0);
				orgIdList.add(role.getPkYmOrgId());
				organizeIdsTree.add(orgIdList);
				if(!"".equals(role.getPkYmRoleId()) && role.getPkYmRoleId() != null) {
					//修改
					filedMap.put("description",role.getRdesc());
					filedMap.put("enabledMark", role.getRstatus());
					filedMap.put("enCode", role.getRid());
					filedMap.put("fullName", role.getRname()+"-"+role.getOrgName());
					filedMap.put("globalMark", 0);
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("sortCode", 0);
					filedMap.put("id", role.getPkYmRoleId());
					result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.updateRoleUrl+"/"+role.getPkYmRoleId(),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
				}else {
					//新增
					filedMap.put("description",role.getRdesc());
					filedMap.put("enabledMark", role.getRstatus());
					filedMap.put("enCode", role.getRid());
					filedMap.put("fullName", role.getRname()+"-"+role.getOrgName());
					filedMap.put("globalMark", 0);
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("sortCode", 0);
					result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveRoleUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
					pkYmRoleId = this.getYmPkRoleIdByRoleName(role.getPkYmOrgId(),role.getRname()+"-"+role.getOrgName());
					this.tblRoleMySqlMapper.updatePkYmbyRoleId(pkYmRoleId,role.getRid());
					if(role.getRname().indexOf("系统管理员") != -1) {
						filedMap = new HashMap<String,Object>(0);
						filedMap.put("objectType","Role");
						filedMap.put("module", moduleStrs);
						filedMap.put("button", buttonStrs);
						filedMap.put("column", columnStrs);
						filedMap.put("form", formStrs);
						filedMap.put("resource", resourceStrs);
						result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.grantRoleRight.replace("#{id}", pkYmRoleId),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
					}else {
						filedMap = new HashMap<String,Object>(0);
						filedMap.put("objectType","Role");
						filedMap.put("module", ptarray);
						result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.grantRoleRight.replace("#{id}", pkYmRoleId),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
					}
				}
			}
		}else {
			List<TblRole> roleList = this.tblRoleMapper.selectAllRoleListToYinMai(orgId);
			for (TblRole role : roleList) {
				filedMap = new HashMap<String,Object>(0);
				organizeIdsTree = new ArrayList<List<String>>(0);
				orgIdList = new ArrayList<String>(0);
				orgIdList.add(role.getPkYmOrgId());
				organizeIdsTree.add(orgIdList);
				if(!"".equals(role.getPkYmRoleId()) && role.getPkYmOrgId() != null) {
					//修改
					filedMap.put("description",role.getRdesc());
					filedMap.put("enabledMark", role.getRstatus());
					filedMap.put("enCode", role.getRid());
					filedMap.put("fullName", role.getRname()+"-"+role.getOrgName());
					filedMap.put("globalMark", 0);
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("sortCode", 0);
					filedMap.put("id", role.getPkYmRoleId());
					result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.updateRoleUrl+"/"+role.getPkYmRoleId(),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
				}else {
					//新增
					filedMap.put("description",role.getRdesc());
					filedMap.put("enabledMark", role.getRstatus());
					filedMap.put("enCode", role.getRid());
					filedMap.put("fullName", role.getRname()+"-"+role.getOrgName());
					filedMap.put("globalMark", 0);
					filedMap.put("organizeIdsTree", organizeIdsTree);
					filedMap.put("sortCode", 0);
					result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveRoleUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
					pkYmRoleId = this.getYmPkRoleIdByRoleName(role.getPkYmOrgId(),role.getRname()+"-"+role.getOrgName());
					this.tblRoleMapper.updatePkYmbyRoleId(pkYmRoleId,role.getRid());
					if(role.getRname().indexOf("系统管理员") != -1) {
						filedMap = new HashMap<String,Object>(0);
						filedMap.put("objectType","Role");
						filedMap.put("module", moduleStrs);
						filedMap.put("button", buttonStrs);
						filedMap.put("column", columnStrs);
						filedMap.put("form", formStrs);
						filedMap.put("resource", resourceStrs);
						result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.grantRoleRight.replace("#{id}", pkYmRoleId),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
					}else {
						filedMap = new HashMap<String,Object>(0);
						filedMap.put("objectType","Role");
						filedMap.put("module", ptarray);
						result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.grantRoleRight.replace("#{id}", pkYmRoleId),filedMap,headerMap,loginStaff,HttpClient.HTTPPUT);
					}
				}
			}
		}
		return ResponseFormat.retParam(1, 200, null);
	}

	private void insertSynchronizeOrgInfoMySql(TblOrganizationMySql com, Map<String, String> headerMap,TblStaffUtil loginStaff) throws Exception {
		HashMap<String, Object> filedMap = new HashMap<String,Object>(0);
		String ymPkOrgId = null;
		filedMap.put("fullName", com.getOrgname());
		filedMap.put("description", com.getMemo());
		filedMap.put("enCode", com.getOrgnumber());
		if(com.getFatherorgid().intValue() == -1) {
			filedMap.put("parentId", -1);
		}else {
			String fatherYmPk = this.tblOrganizationMySqlMapper.selectYmPkOrgid(com.getFatherorgid());
			filedMap.put("parentId", fatherYmPk);
		}
		filedMap.put("sortCode", com.getOrderid());
		filedMap.put("enabledMark", 1);
		String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveOrgUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		ymPkOrgId = this.getYmPkOrgIdByOrgName(com.getOrgname());
		this.tblOrganizationMySqlMapper.updateYmPkOrgid(ymPkOrgId,com.getOrgid());
	}



	private void insertSynchronizeOrgInfoMySql(List<TblOrganizationMySql> companyList,Map<String, String> headerMap,String fatherYmPk,TblStaffUtil loginStaff) throws Exception {
		List<TblOrganizationMySql> orgList = null;
		HashMap<String, Object> filedMap = null;
		String ymPkOrgId = null;
		for (TblOrganizationMySql com : companyList) {
			filedMap = new HashMap<String,Object>(0);
			filedMap.put("fullName", com.getOrgname());
			filedMap.put("description", com.getMemo());
			filedMap.put("enCode", com.getOrgnumber());
			if(fatherYmPk == null) {
				filedMap.put("parentId", -1);
			}else {
				filedMap.put("parentId", fatherYmPk);
			}
			filedMap.put("sortCode", com.getOrderid());
			filedMap.put("enabledMark", 1);
			String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveOrgUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
			System.out.println(result);
			ymPkOrgId = this.getYmPkOrgIdByOrgName(com.getOrgname());
			this.tblOrganizationMySqlMapper.updateYmPkOrgid(ymPkOrgId,com.getOrgid());
			
			orgList = this.tblOrganizationMySqlMapper.selectCompanyListParentId(com.getOrgid().intValue());
			
			if(orgList != null && orgList.size() != 0) {
				this.insertSynchronizeOrgInfoMySql(orgList,headerMap,ymPkOrgId,loginStaff);
			}
		}
	}
	/**
	 * 同步公司下的所有部门信息
	 * @param allComList
	 * @param headerMap
	 * @param object
	 */
	private void synchronizeDeptInfoMySql(List<TblOrganizationMySql> allComList, Map<String, String> headerMap,String fatherYmPk,TblStaffUtil loginStaff) throws Exception {
		List<TblOrganizationMySql> orgList = null;
		HashMap<String, Object> filedMap = null;
		String ymPkOrgId = null;
		
		for (TblOrganizationMySql com : allComList) {
			filedMap = new HashMap<String,Object>(0);
			filedMap.put("fullName", com.getOrgname());
			filedMap.put("description", com.getMemo());
			filedMap.put("enCode", com.getOrgnumber());
			filedMap.put("enabledMark", 1);
			filedMap.put("parentId", fatherYmPk);
			filedMap.put("sortCode", com.getOrderid());
			String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveDeptUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
			ymPkOrgId = this.getYmPkOrgIdByOrgName(com.getOrgname());
			this.tblOrganizationMySqlMapper.updateYmPkOrgid(ymPkOrgId,com.getOrgid());
			orgList = this.tblOrganizationMySqlMapper.selectDeptListByOrgId(com.getOrgid());
			if(orgList != null && orgList.size() != 0) {
				this.synchronizeDeptInfoMySql(orgList,headerMap,ymPkOrgId,loginStaff);
			}
		}
	}


	/**
	 * 同步公司下的所有部门信息
	 * @param allComList
	 * @param headerMap
	 * @param object
	 */
	private void synchronizeDeptInfo(List<TblOrganization> allComList, Map<String, String> headerMap,String fatherYmPk,TblStaffUtil loginStaff) throws Exception {
		List<TblOrganization> orgList = null;
		HashMap<String, Object> filedMap = null;
		String ymPkOrgId = null;
		
		for (TblOrganization com : allComList) {
			filedMap = new HashMap<String,Object>(0);
			filedMap.put("fullName", com.getOrgname());
			filedMap.put("description", com.getMemo());
			filedMap.put("enCode", com.getOrgnumber());
			filedMap.put("enabledMark", 1);
			filedMap.put("parentId", fatherYmPk);
			filedMap.put("sortCode", com.getOrderid());
			String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveDeptUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
			ymPkOrgId = this.getYmPkOrgIdByOrgName(com.getOrgname());
			this.tblOrganizationMapper.updateYmPkOrgid(ymPkOrgId,com.getOrgid());
			orgList = this.tblOrganizationMapper.selectDeptListByOrgId(com.getOrgid());
			if(orgList != null && orgList.size() != 0) {
				this.synchronizeDeptInfo(orgList,headerMap,ymPkOrgId,loginStaff);
			}
		}
	}

	private void insertSynchronizeOrgInfo(TblOrganization com, Map<String, String> headerMap,TblStaffUtil loginStaff) throws Exception {
		HashMap<String, Object> filedMap = new HashMap<String,Object>(0);
		String ymPkOrgId = null;
			
		filedMap.put("fullName", com.getOrgname());
		filedMap.put("description", com.getMemo());
		filedMap.put("enCode", com.getOrgnumber());
		if(com.getFatherorgid().intValue() == -1) {
			filedMap.put("parentId", -1);
		}else {
			String fatherYmPk = this.tblOrganizationMapper.selectYmPkOrgid(com.getFatherorgid());
			filedMap.put("parentId", fatherYmPk);
		}
		filedMap.put("sortCode", com.getOrderid());
		filedMap.put("enabledMark", 1);
		String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveOrgUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
		ymPkOrgId = this.getYmPkOrgIdByOrgName(com.getOrgname());
		this.tblOrganizationMapper.updateYmPkOrgid(ymPkOrgId,com.getOrgid());
	}

	private void insertSynchronizeOrgInfo(List<TblOrganization> companyList, Map<String, String> headerMap,String fatherYmPk,TblStaffUtil loginStaff) throws Exception {
		List<TblOrganization> orgList = null;
		HashMap<String, Object> filedMap = null;
		String ymPkOrgId = null;
		for (TblOrganization com : companyList) {
			filedMap = new HashMap<String,Object>(0);
			filedMap.put("fullName", com.getOrgname());
			filedMap.put("description", com.getMemo());
			filedMap.put("enCode", com.getOrgnumber());
			if(fatherYmPk == null) {
				filedMap.put("parentId", -1);
			}else {
				filedMap.put("parentId", fatherYmPk);
			}
			filedMap.put("sortCode", com.getOrderid());
			filedMap.put("enabledMark", 1);
			String result = DealUserToken.dealYmUrlMethod(YinMaiUrlStatic.interfaceUrl+YinMaiUrlStatic.saveOrgUrl,filedMap,headerMap,loginStaff,HttpClient.HTTPPOST);
			System.out.println(result);
			ymPkOrgId = this.getYmPkOrgIdByOrgName(com.getOrgname());
			this.tblOrganizationMapper.updateYmPkOrgid(ymPkOrgId,com.getOrgid());
			orgList = this.tblOrganizationMapper.selectCompanyListParentId(com.getOrgid().intValue());
			
			if(orgList != null && orgList.size() != 0) {
				this.insertSynchronizeOrgInfo(orgList,headerMap,ymPkOrgId,loginStaff);
			}
		}
		
		
	}
	private String getYmPkOrgIdByOrgName(String orgname) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String fid = null;
		try {
			con = BaseDao.getInstance().getConnection();
			ps = con.prepareStatement("SELECT F_Id FROM base_organize WHERE F_FullName = '"+orgname+"'");
			rs = ps.executeQuery();
			
			while (rs.next()) {
				fid = rs.getString("F_Id");
			}
		}finally {
			BaseDao.getInstance().close(con,rs,ps);
		}
		return fid;
	}
	
	private String getYmPkRoleIdByRoleName(String pkYmOrgId, String rname) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String fid = null;
		try {
			con = BaseDao.getInstance().getConnection();
			ps = con.prepareStatement("SELECT role.F_Id FROM base_role role LEFT JOIN base_organize_relation ORGRE ON ROLE.F_Id = ORGRE.F_Object_Id AND ORGRE.F_Object_Type = 'Role' WHERE role.F_FullName = '"+rname+"' AND ORGRE.F_Organize_Id = '"+pkYmOrgId+"'");
			rs = ps.executeQuery();
			
			while (rs.next()) {
				fid = rs.getString("F_Id");
			}
		}finally {
			BaseDao.getInstance().close(con,rs,ps);
		}
		return fid;
	}

}
